package cn.lazydong.dbproperties.config;

import cn.lazydong.dbproperties.DbPropertiesUtil;
import cn.lazydong.dbproperties.exception.NotFundPropertiesException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author HeLingdong
 */
@Configuration
@ConditionalOnBean(DbPropertiesCustom.class)
public class DbPropertiesInit {

    @Resource
    Map<String, DbPropertiesCustom> dbCustomPropertiesMap;

    @PostConstruct
    public void init() {
        if (CollectionUtils.isEmpty(dbCustomPropertiesMap)) {
            return;
        }
        Map<String, Object> allCustomPropertyMap = new HashMap<>();
        for (DbPropertiesCustom value : dbCustomPropertiesMap.values()) {
            Map<String, Object> customParam = value.getCustomParam();
            if (CollectionUtils.isEmpty(customParam)) {
                continue;
            }
            allCustomPropertyMap.putAll(customParam);
        }
        if (!CollectionUtils.isEmpty(allCustomPropertyMap)) {
            for (Map.Entry<String, Object> entry : allCustomPropertyMap.entrySet()) {
                DbPropertiesUtil.addPropertySource(entry.getKey(), entry.getValue());
                DbPropertiesUtil.refresh(entry.getKey(), entry.getValue());
            }
        }
        // 检测
        Map<String, Object> allValueFromDb = DbPropertiesUtil.getAllValueFromDb();
        if (CollectionUtils.isEmpty(allValueFromDb)) {
            return;
        }
        Set<String> dbPropertySet = allValueFromDb.keySet();
        Set<String> customPropertySet = allCustomPropertyMap.keySet();

        Set<String> missConfigSet = new HashSet<>();
        dbPropertySet.forEach(temp -> {
            if (!customPropertySet.contains(temp)) {
                missConfigSet.add(temp);
            }
        });
        if (!missConfigSet.isEmpty()) {
            StringBuilder msgBuilder = new StringBuilder("The following configurations are missing: ");
            missConfigSet.forEach(temp -> msgBuilder.append(temp).append(","));
            msgBuilder.deleteCharAt(msgBuilder.length() - 1);
            throw new NotFundPropertiesException(msgBuilder.toString());
        }
    }
}
